<script setup>
import { search as drugSearch } from "@/api/pharmacy/drug"
import { search as drugProcessSearch } from "@/api/drug/drugProcess"
import { list as doctorSearch } from "@/api/user/doctor"
import { useRouter, useRoute } from "vue-router";
import {
  ref,
  reactive,
  nextTick,
  onMounted, onBeforeMount
} from 'vue'
import {CircleCloseFilled} from "@element-plus/icons-vue";
import { create, update, detail } from "@/api/recipeTemplate/temp";
import {ElMessage} from "element-plus";
const formInline = reactive({
  doctor_id: "",
  classic: 2,
  name: "",
  doctor_name: "",
  drug_process_id: "",
  drug_process_name: "",
  content: ""
})
const router = useRouter();
const route = useRoute();
const drugOptions = ref([])
const drugProcessOptions = ref([])
const doctorOptions = ref([])
const drugId = ref(null)
const selDrugList = ref([])
const historyTemplateList = ref([])
const numberRef = ref({})
const numberIndex = ref(0)
const ruleFormRef = ref()
const tempId = ref(null)
const setNumberRef = (el, index) => {
  console.log(selDrugList.value.length-1, "olx")
  if (el) {
    numberRef.value[numberIndex.value] = el;
  }
};
const clearDrug = () => {
  selDrugList.value = []
}
const remoteMethod = async (query) => {
  const res = await drugSearch({ name: query });
  drugOptions.value = res.data
}
const drugProcessRemoteMethod = async (query) => {
  const res = await drugProcessSearch({ name: query });
  drugProcessOptions.value = res.data
}
const doctorRemoteMethod = async (query) => {
  const res = await doctorSearch({ name: query });
  doctorOptions.value = res.data.data
}
const drugChange = (value) => {
  let selDrugIndex = selDrugList.value.findIndex(item => item.id === value);
  console.log(selDrugIndex, selDrugList, numberRef.value)
  if (selDrugIndex === -1) {
    let drugIndex = drugOptions.value.findIndex(item=>item.id === value);
    const drug = drugOptions.value[drugIndex]
    selDrugList.value.push(drug)
    numberIndex.value = selDrugList.value.length-1
  }
  drugId.value = null
  nextTick(() => {
    numberRef.value[selDrugIndex === -1 ? numberIndex.value : selDrugIndex].focus();
  });
}

const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const options = { ...formInline }
      const doctor = doctorOptions.value.find(item=>item.id === options.doctor_id);
      options.doctor_name = doctor.name;
      const drugProcess = drugProcessOptions.value.find(item=>item.id === options.drug_process_id);
      options.drug_process_name = drugProcess.name;
      const content = [];
      for (const drug of selDrugList.value) {
        content.push({
          drug_id: drug.id,
          drug_num: drug.drug_num,
          unit_id: drug.unit_id,
        })
      }
      options.content = JSON.stringify(content)
      if (options.id) {
        await update(options)
      } else {
        await create(options)
      }
      ElMessage.success("创建成功");
      setTimeout(() => {
        back()
      }, 1000)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const delDrug = (index) => {
  console.log("index=", index)
  console.log("selDrugList=", selDrugList)
  console.log("numberIndex=", numberIndex)
  console.log("numberRef=", numberRef)
  selDrugList.value.splice(index, 1)
  numberIndex.value -= 1
  delete numberRef.value[index]
}

const back = ()=> {
  router.go(-1)
}

const getDetail = async () => {
  if (!tempId.value) {
    return false
  }
  const res = await detail({ id: tempId.value });
  formInline.id = res.data.id;
  formInline.doctor_id = res.data.doctor_id;
  formInline.doctor_name = res.data.doctor_name;
  formInline.name = res.data.name;
  formInline.classic = res.data.classic;
  formInline.status = res.data.status;
  formInline.drug_process_id = res.data.drug_process_id;
  formInline.drug_process_name = res.data.drug_process_name;
  const content = [];
  for (const drug of res.data.content) {
    content.push({
      id: drug.drug_id,
      drug_num: drug.drug_num,
      unit_id: drug.unit_id,
      name: drug.name,
    })
  }
  selDrugList.value = content;

  await doctorRemoteMethod(res.data.doctor_name)
  await drugProcessRemoteMethod(res.data.drug_process_name)
}

onBeforeMount(() => {
  tempId.value = route.query.id
  getDetail()
})
onMounted(()=>{
})
</script>

<template>
  <div class="pageContent">
    <div class="detailContainer">
      <div class="title">{{ tempId?'编辑':'新增' }}模版方</div>
      <div>
        <el-form ref="ruleFormRef" :model="formInline" label-position="right" label-width="auto"
                 :rules="rules">
          <el-form-item label="归属医生：" :rules="[{required: true,message: '',trigger: 'blur',},]">
            <el-select v-model="formInline.doctor_id" filterable remote
                       :remote-method="doctorRemoteMethod"
                       :placeholder="`请选择归属医生`">
              <el-option v-for="(sel, selKey) in doctorOptions" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板名称：" :rules="[{required: true,message: '',trigger: 'blur',},]">
            <el-input v-model="formInline.name" placeholder="请输入模板名称" clearable />
          </el-form-item>
          <el-form-item label="药态：" :rules="[{required: true,message: '',trigger: 'blur',},]">
            <el-select v-model="formInline.drug_process_id" filterable remote
                       :remote-method="drugProcessRemoteMethod"
                       :placeholder="`请选择药态`">
              <el-option v-for="(sel, selKey) in drugProcessOptions" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="药品名称：">
            <el-select v-model="drugId" filterable remote
                       :remote-method="remoteMethod"
                       @change="drugChange"
                       :placeholder="`请选择药品名称`">
              <el-option v-for="(sel, selKey) in drugOptions" :key="selKey" :value="sel.id" :label="sel.name || sel.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 药品块 -->
        <el-row class="template-body">
          <el-col :span="24">
            <div class="tb-left">
              <div class="tb-l-box flex justify-start items-start content-start flex-wrap i-scrollbar-hide">
                <div class="tb-l-list relative mb-8 template" v-for="(d, dk) in selDrugList" :key="dk">
                  <el-icon class="tb-ll-icon absolute" style="font-size: 16px; color: rgb(237, 64, 20);" @click="delDrug(dk)">
                    <circle-close-filled />
                  </el-icon>
                  <div class="tb-ll-name font-14 txt-color-85 flex justify-start items-center">
                    <div class="flex-1 overflow-ellipsis">{{ d.name }} </div>
                  </div>
                  <div class="tb-ll-num font-12 txt-color-85 flex justify-start items-center"> 用量：
                    <el-input-number v-model="d.drug_num" :min="1" :ref="setNumberRef" class="tb-ll-n-input" size="small"></el-input-number>
                    &nbsp;g
                  </div>
                </div>
              </div>
              <el-button class="absolute btn-clear" type="primary" @click="clearDrug" size="small">清除</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="bottomBtn">
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.comPage {
  padding: 15px;
}
.template-body {
  .tb-left {
    width: calc(100% - 8px);
    border: 1px solid rgba(0, 0, 0, 0.15);
    height: 432px;
    border-radius: 5px;
    .btn-clear {
      bottom: 6px;
      right: 14px;
    }
    .tb-l-box {
      width: 100%;
      height: 396px;
      padding: 8px 8px 0;
      overflow-y: auto;
      overflow-x: hidden;
      box-sizing: border-box;
    }
    .tb-l-list {
      width: calc(33% - 6px);
      height: 64px;
      border: 1px solid #1890ff;
      border-radius: 5px;
      background: #eff3f7;
      margin-right: 10px;
      padding: 8px;
      box-sizing: border-box;
      &:nth-of-type(3n) {
        margin-right: 0;
      }
      .tb-ll-icon {
        top: 4px;
        right: 4px;
        cursor: pointer;
      }
      .tb-ll-name {
        width: 90%;
        height: 20px;
        line-height: 20px;
      }
      .tb-ll-num {
        width: 100%;
      }
      .tb-ll-n-input {
        width: calc(100% - 80px);
      }
    }
  }
  .tb-right {
    width: 100%;
    height: 400px;
    .tb-r-title {
      width: 100%;
      height: 40px;
      line-height: 40px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      background: rgba(255, 255, 255, 0.02);
      border-top-right-radius: 5px;
      border-top-left-radius: 5px;
      text-align: center;
      color: #1890ff;
    }
    .tb-r-body {
      width: 100%;
      height: 360px;
      background: #f4faff;
      border-bottom-left-radius: 5px;
      border-bottom-right-radius: 5px;
      padding: 20px 12px 20px 20px;
      overflow-x: hidden;
      overflow-y: auto;
      .tb-rb-content {
        width: calc(100% - 24px);
        margin-left: 24px;
        max-height: 34px;
        line-height: 17px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      label {
        width: 100%;
        height: 21px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
